module startclock(SW,CLOCK_50,KEY,year1,year2,month,day,min,sec,hour);
     input[17:0] SW;
     input CLOCK_50;
     input[3:0] KEY;
     output reg[5:0] min,sec,hour;
     output reg[9:0] year1,year2,month,day;   
     integer i;
     reg [17:0]saveclock;
     wire clk_1;
     div_clock_1hz dd1(CLOCK_50,clk_1);


always@(posedge clk_1,negedge KEY[0],negedge KEY[1],negedge KEY[2])//show time and set time
       if(!KEY[0])
         begin
           saveclock<=SW;   
           if(saveclock[17:12]<=23)    //set hour SW[17:12]
           hour<=saveclock[17:12];
           else
           hour<=23;
           
           if(saveclock[11:6]<=59)  //set min SW[11:6]
           min<=saveclock[11:6];
           else
           min<=59;
           
           if(saveclock[5:0]<=59)  //set sec SW[5:0]
           sec<=saveclock[5:0];
           else
           sec<=59;  
         end
       else if(!KEY[1])
           begin
             
             if(SW[4:0]<=31)
             day<=SW[4:0];
             else
             day<=1;
             
             if(SW[8:5]<=12)
             month<=SW[8:5];
             else
             month<=12;
             
            
              
            // year1<=2'd20;
             
           end
           
           
         else if(!KEY[2])
         begin
           
            if(SW[17:11]<=99)
             year1<=SW[17:11];
             else
             year1<=99;
           if(SW[10:4]<=99)
             year2<=SW[17:4];
             else
             year2<=99;
           
           
           end
    
       else 
	   begin          //run clock
           if(sec<6'd59) sec<=sec+1;
           else 
               begin
	           sec<=6'd0;
	           if(min<6'd59) min<=min+1;
	           else 
	               begin 
	               min<=6'd0;
	               if(hour<5'd23)hour<=hour+1;
	               else
	                   begin 
                       hour<=6'd0;
                       if(day<31) day<=day+1;
                       else 
                           begin
                           day<=5'd1;
                           if(month<4'd11) month<=month+1;
                           else
                               begin
                               month<=4'd1;
                               if(year2<7'd99) year2<=year2+1;
                               else 
                               if(year1<7'd99) year1<=year1+1;
                               else
                               begin
                               year1<=7'd0;year2<=7'd0;month<=4'd1;day<=5'd1;
                               hour<=6'd0;min<=6'd0;sec<=6'd0;
                               end
                               end
                           end
                      end
                   end
               end
           end
endmodule 